import { Component, OnInit } from '@angular/core';
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Router, ActivatedRoute} from "@angular/router";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {AccountsService} from "../accounts.service";
import {MsgConstants} from "../../../../constants/constants";

declare var $;
@Component({
  selector: 'app-account-authority',
  templateUrl: './account-authority.component.html'
})
export class AccountAuthorityComponent implements OnInit {

  accountId: string;
  //所有权限数组
  allAuthority: Array<string> = [];

  roleAuthority: Array<string> = [];
  //处理后的权限树
  AuthorityTree: Array<string> = [];

  //权限数组[菜单，资源，操作]
  authoritys:Array<string>=[];

  //配置id数组
  authorityConfigs :Array<string> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private accountsService: AccountsService,
    private responseUtil: ResponseUtil,
  ) {  }

  ngOnInit() {
    //初始化导航
    this.pushPage();
    if (!!this.route.snapshot.params["accountId"]) {
      this.accountId = this.route.snapshot.params["accountId"];
      //初始化菜单树
      this.initMenuZTree(this.accountId);
    }
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("账户管理", "分配权限", path);
  }
  /**
   * 初始化各种权限id（菜单）
   */
  initMenuZTree(accountId) {
    this.accountsService.initAssignAuthority(accountId).subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取初始化权限树日志
   * @param result
   */
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.allAuthority = result.data.allAuthorityList;
      this.roleAuthority = result.data.roleAuthorityList;
      this.AuthorityTree = this.authorityTree(result.data.allAuthorityList, result.data.roleAuthorityList);
      this.initRoleAuthorizationZTree(this.AuthorityTree);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *  菜单树处理
   * @param menus
   * @param authorityConfigId  :,authorityConfigId
   */
  initRoleAuthorizationZTree(AuthorityList) {
    var zNodes = AuthorityList;

    var setting = {
      check: {
        enable: true,
        // chkboxType :{ "Y" : "s", "N" : "s" }
        // chkboxType :{"Y" : "ps", "N" : "ps"}
        chkboxType :{ "Y" : "ps", "N" : "s" }
      },
      view: {
        dblClickExpand: true,
        selectedMulti: true
      },
      data: {
        simpleData: {
          enable: true
        }
      },

      callback: {},
    };
    //把树放进页面
    $.fn.zTree.init($("#account_allot_authority_tree"), setting, zNodes);
  }


  /**
   *
   * @param allAuthority
   * @param roleAuthority
   * @returns {Array}
   */
  private authorityTree(allAuthority, roleAuthority): any[] {
    if (roleAuthority) {
      $.each(allAuthority, function (allIndex, allAuth) {
        //已被授权的权限
        $.each(roleAuthority, function (roleIndex, roleAuth) {
          //如果已被授权，初始化时勾选
          if (roleAuth.id == allAuth.id) {
            allAuth.checked = true;
          }
        });
      });
    }
    return allAuthority;
  }

  /**
   * 实现添加
   */
  saveRoleAuthorization() {
    this.processingSelectedData();
    if (!!this.accountId && !!this.authoritys) {
      this.accountsService.assignAuhtoritys(this.accountId, this.authoritys, this.authorityConfigs).subscribe(
        result => this.responseUtil.success(result, this.processAccountAuthorityResult),
        message => this.responseUtil.error(message)
      );
    }
  }

  /**
   * 处理勾中复选框数据
   */
  processingSelectedData() {
    let treeObj = $.fn.zTree.getZTreeObj("account_allot_authority_tree");
    let nodes = treeObj.getCheckedNodes();
    for (var i = 0; i < nodes.length; i++) {
      this.authoritys.push(nodes[i].id);
      this.authorityConfigs.push(nodes[i].authorityConfigId);
    }
  }


  /**
   * 获取角色授权日志
   * @param result
   */
  private processAccountAuthorityResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //清空数组
      this.authoritys.splice(0, this.authoritys.length);
      this.dialogService.modalSuccess("分配权限成功！", ()=>this.cancelRoleAuthorization());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
      //清空数组
      this.authoritys.splice(0, this.authoritys.length);
    }
  }

  /**
   * 取消添加
   */
  cancelRoleAuthorization() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }


}
